import {Controller, Post, required} from '../decorator/router'
import {getSocketIdByUserId, updateSocketIdById} from '../service/socket'
import {login} from '../decorator/auth'
import {
  getDialogByUserId,
  getMessageWithSomeOne,
  getMultiMessagesByDialogId,
  sendMessage,
  sendMessageByDialogId, signSingleDialog, signSingleMessage
} from '../service/message'
import {getUserById} from '../service/user'
import {getDialogInfoByDialogId, getUnreadCountByUserId} from '../service/dialog'
import {myEvent} from '../utils/common'

@Controller('/socket')
export class WebSocket {
  @Post('/login')
  @login
  @required({
    body: ['id']
  })
  async login(ctx, next) {
    const {id} = ctx.request.body
    await updateSocketIdById(ctx.session.userId, id)
    ctx.body = {
      result: 1,
      mes: '即时聊天登录成功!'
    }
    const user = await getSocketIdByUserId(ctx.session.userId)
    console.log(`${user.nickname} 已连接 ${new Date().toLocaleString()}`)
  }

  @Post('/send')
  @login
  @required({
    body: ['sendTo', 'content', 'type']
  })
  async send(ctx, next) {
    const user = ctx.userInfo
    let {sendTo, content, type} = ctx.request.body
    type = Number(type)
    if (type === 0) {
      const toUser = await getSocketIdByUserId(sendTo)
      if (user && toUser) {
        let message = await sendMessage(user._id, sendTo, content)
        ctx.body = {
          result: 1,
          mes: '发送成功'
        }
        myEvent.emit('receive message', message, toUser)
        myEvent.emit('unread count', await getUnreadCountByUserId(toUser._id), toUser)
      } else {
        ctx.body = {
          result: 0,
          mes: '发送失败'
        }
      }
    } else {
      const dialog = await getDialogInfoByDialogId(sendTo, {socketId: 1})
      if (dialog) {
        const message = await sendMessageByDialogId(user._id, sendTo, content)
        if (message) {
          ctx.body = {
            result: 1,
            mes: '发送成功'
          }
          // 通知群组其他人
          let members = dialog.members
          members = members.filter(item => String(item._id) !== String(user._id))
          members.forEach(async item => {
            myEvent.emit('receive message', message, item)
            const unread = await getUnreadCountByUserId(item._id)
            myEvent.emit('unread count', unread, item)
          })
        } else {
          ctx.body = {
            result: 0,
            mes: '发送失败，你还没有加入该群组'
          }
        }
      } else {
        ctx.body = {
          result: 0,
          mes: '聊天室不存在'
        }
      }
    }
  }

  @Post('/sign')
  @login
  async sign(ctx, next) {
    const user = ctx.userInfo
    const {toUserId, dialogId, messageId} = ctx.request.body
    if (toUserId) {
      // 标记一对一聊天信息
      const dialog = await getDialogByUserId(user._id, toUserId)
      if (dialog) {
        await signSingleDialog(dialog._id, user._id)
      }
      ctx.body = {
        data: await getUnreadCountByUserId(user._id),
        result: 1,
        mes: '标记成功'
      }
    } else if (dialogId) {
      // 标记单个聊天室信息
      await signSingleDialog(dialogId, user._id)
      ctx.body = {
        data: await getUnreadCountByUserId(user._id),
        result: 1,
        mes: '标记成功'
      }
    } else if (messageId) {
      // 标记单个信息
      await signSingleMessage(user._id, messageId)
      ctx.body = {
        data: await getUnreadCountByUserId(user._id),
        result: 1,
        mes: '标记成功'
      }
    } else {
      ctx.body = {
        result: 0,
        mes: '参数错误'
      }
    }
  }

  @Post('/messages')
  @login
  async getMessages(ctx, next) {
    const {userId, dialogId, skip, size} = ctx.request.body
    if (userId) {
      ctx.body = await getMessageWithSomeOne(ctx.session.userId, userId, skip, size)
    } else if (dialogId) {
      ctx.body = await getMultiMessagesByDialogId(ctx.session.userId, dialogId, skip, size)
    } else {
      ctx.body = {
        result: 0,
        mes: '参数错误'
      }
    }
  }

  @Post('/roomInfo')
  @login
  async getRoomInfo(ctx, next) {
    const {userId, dialogId} = ctx.request.body
    if (userId) {
      const userInfo = await getUserById(userId, ctx.session.userId)
      if (userInfo) {
        ctx.body = {
          data: {
            name: userInfo.nickname,
            icon: userInfo.avatar,
            _id: userInfo._id,
            isFriend: userInfo.isFriend,
            type: 0
          },
          result: 1
        }
      } else {
        ctx.body = {
          result: 0,
          mes: '没有查询到该用户信息'
        }
      }
    } else if (dialogId) {
      const dialogInfo = await getDialogInfoByDialogId(dialogId)
      if (dialogInfo) {
        ctx.body = {
          data: {
            name: dialogInfo.name,
            icon: dialogInfo.icon,
            _id: dialogInfo._id,
            type: dialogInfo.type
          },
          result: 1
        }
      } else {
        ctx.body = {
          result: 0,
          mes: '没有查询到聊天室信息'
        }
      }
    } else {
      ctx.body = {
        result: 0,
        mes: '参数错误'
      }
    }
  }
}
